import { rolePermission } from '@/api/systemManagement/accountManagement'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { constantRoutes } from '@/router'
import router from '../../router/index'
export default {
  namespaced: true,
  state () {
    return {
      token: getToken(),
      menuList: [],
      username: localStorage.getItem('user_name'),
      routes: constantRoutes || [],
      sideBarItem: {},
      nowSideSelect: '',
      btnList: []
    }
  },
  mutations: {
    setToken (state, payload) {
      state.token = payload.access_token
      state.username = payload.user_name
      localStorage.setItem('user_name', payload.user_name)
      localStorage.setItem('role_id', payload.role_id)
      setToken(payload.access_token)
    },
    delToken (state) {
      state.token = null
      removeToken()
    },
    storeMenuList (state, payload) {
      state.menuList = payload
      state.sideBarItem = payload[0]
    },
    updateRoutes (state, payload) {
      state.routes = [...constantRoutes, ...payload]
    },
    storeSideBarItem (state, payload) {
      state.sideBarItem = payload
      state.nowSideSelect = payload.menuList[0].path
    },
    storeBtnList (state, payload) {
      // console.log(payload)
      state.btnList = payload
    }
  },
  actions: {
    async getMenuList (context, payload) {
      const res = await rolePermission(payload)
      if (!res.data.length) {
        // this.$router.push('/login')
      }
      context.commit('storeMenuList', res.data)
      return res
    },
    async loginOut (context) {
      context.commit('delToken')
      window.localStorage.clear()
      router.push('/login')
    }
  }
}
